﻿using static System.Runtime.InteropServices.JavaScript.JSType;

namespace orleans_demo.Services
{
    public interface IProfileGrain :  IGrainWithStringKey
    {
        Task<string> GetNameAsync();

        Task SetNameAsync(string name);
    }


    [Serializable]
    public class ProfileState
    {
        public string Name { get; set; }

        public Date DateOfBirth { get; set; }
    }

    /// <summary>
    /// 使用 PersistentState
    /// </summary>
    [GrainType("ProfileService")]
    public class ProfileGrain :Grain,IProfileGrain
    {
        private readonly IPersistentState<ProfileState> _profile;
        readonly IDataServiceClient _dataServiceClient;

        public ProfileGrain(
             IDataServiceClient dataServiceClient,
            [PersistentState("profile", "SnapshotStore")]
        IPersistentState<ProfileState> profile)
        {
            _dataServiceClient = dataServiceClient;
            //配置文件状态在注入到构造函数时不会被加载，因此在注入时访问它是无效操作。 在调用 OnActivateAsync 之前加载状态。
            _profile = profile;
        }

        public Task<string> GetNameAsync() => Task.FromResult(_profile.State.Name);

        public async Task SetNameAsync(string name)
        {
           await _dataServiceClient.MyMethod();
            _profile.State.Name = name;
            await _profile.WriteStateAsync();
        }
    }
}
